package material

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/framework/model/entity"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

// SaveMaterialTemplateWords 保存素材模板文案-关键词
func (m *sMaterial) SaveMaterialTemplateWords(ctx context.Context, tid uint, words ...model.MaterialTemplateWordsSaveItem) error {
	// 素材模板ID
	if tid == 0 {
		return gerror.New(`缺少素材模板ID`)
	}

	// 获取素材ID
	materialMap, err := m.ProcessMaterialMapById(
		ctx, utils.NewArray(words).ArrayColumnsUniqueUnit(`material_id`)...,
	)
	if err != nil {
		return err
	}

	// 素材模板关键词
	if len(words) == 0 {
		return gerror.New(`素材模板文案词不存在`)
	}
	columns := dao.MaterialTemplateWords.Columns()

	// 初始化
	ws := make([]entity.MaterialTemplateWords, 0)
	for _, word := range words {
		if word.Id == 0 {
			// 验证是否已存在[素材ID]
			isExists, _ := m.CheckTemplateWordsExists(ctx, g.Map{
				columns.TemplateId: tid,
				columns.MaterialId: word.MaterialId,
				columns.MaterialX:  word.MaterialX,
				columns.MaterialY:  word.MaterialY,
			})
			// 存在不创建
			if isExists {
				continue
			}
		}
		// 素材信息不存在
		material, ok := materialMap[word.MaterialId]
		if !ok {
			return gerror.New(`素材不存在`)
		}
		// 整理数据
		item := entity.MaterialTemplateWords{
			Id:             word.Id,
			TemplateId:     tid,
			MaterialId:     word.MaterialId,
			ExampleWords:   word.ExampleWords,
			WordsFont:      word.WordsFont,
			WordsFontColor: word.WordsFontColor,
			WordsX:         word.WordsX,
			WordsY:         word.WordsY,
			LayerPosition:  word.LayerPosition,
			FontFamily:     word.FontFamily,
			WordsType:      uint(word.WordsType),
			MaterialX:      word.MaterialX,
			MaterialY:      word.MaterialY,
			MaterialColor:  word.MaterialColor,
			Url:            material.Url,
		}
		ws = append(ws, item)
	}
	// 数据未更新
	if len(ws) == 0 {
		return nil
	}
	_, err = dao.MaterialTemplateWords.Ctx(ctx).Save(ws)
	return err
}

// DeleteMaterialTemplateWords 删除素材模板文案词
func (m *sMaterial) DeleteMaterialTemplateWords(ctx context.Context, tid uint, wordsId ...uint) error {
	if tid == 0 {
		return gerror.New(`缺少素材模板ID`)
	}
	// 搜索条件
	where := g.Map{
		dao.MaterialTemplateWords.Columns().TemplateId: tid,
	}
	if len(wordsId) > 0 {
		where[dao.MaterialTemplateWords.Columns().Id] = wordsId
	}
	// 删除数据
	_, err := dao.MaterialTemplateWords.Ctx(ctx).
		Where(where).
		Delete()
	return err
}
